package com.ffapp.demo.map;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import my.ActivityTool;

public class MapLocationActivity extends BasisActivity implements LocationSource,
        AMapLocationListener { // Inputtips.InputtipsListener

    public static void toMapActivity(Activity context,double latitude,double longtitude,String  addressTitle,String addressDes){
        Bundle bundle = new Bundle();
        bundle.putDouble("la",latitude);
        bundle.putDouble("long",longtitude);
        bundle.putString("title",addressTitle);
        bundle.putString("des",addressDes);
        ActivityTool.skipActivity(context,MapLocationActivity.class,bundle);
    }

    private AMap aMap;
    private MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    double latitude = -1;
    double longtitude = -1;
    String addressTitle;
    String addressDes;

    @BindView(R.id.text_address_title)
    TextView text_address_title;
    @BindView(R.id.text_address_des)
    TextView text_address_des;

    @Override
    public void initViews() {
        super.initViews();
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.map_location_activity);
        setTitle("位置信息");
        setTitleLeftButton(null);

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        initMap();

        Bundle bundle = getIntent().getExtras();
        latitude = bundle.getDouble("la");
        longtitude = bundle.getDouble("long");
        addressTitle = bundle.getString("title");
        addressDes = bundle.getString("des");

        if(latitude == 0 && longtitude == 0){
            showToast("没有定位数据");
            finish();
            return;
        }
//        setCurrentLocation();

        text_address_title.setText(addressTitle);
        text_address_des.setText(addressDes);

    }



    /**
     * 初始化
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            if(AMapLocUtil.mMapCenterLatLng != null){
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AMapLocUtil.mMapCenterLatLng, 16f));
            }
            setUpMap();
        }
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                setCurrentLocation();
            }
        });

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
//                LogUtil.i("onCameraChangeFinish---->"+cameraPosition.zoom);
            }
        });
//        aMap.setInfoWindowAdapter(new CarLocationWinAdapter(mContext,false));
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.getUiSettings().setZoomControlsEnabled(true);
        aMap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_BUTTOM);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    private void setCurrentLocation(){
        if(latitude == -1 || longtitude == -1)return;
        LatLng latLng = new LatLng(latitude,longtitude);
//        LatLng latLng = AMapUtil.convert84ToLatLng();
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f));
        MarkerOptions markerOptions  = new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.user_locsign_map_icon_pin))
                .infoWindowEnable(false)
                .anchor(0.5f,0.9f)
                .position(latLng)
                .visible(true);
        aMap.addMarker(markerOptions);
    }




    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        EventBus.getDefault().unregister(this);
    }

    boolean isFirstMyLocation = true;
    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
//        Log.i("MY", "onLocationChanged");
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);
//                if(isFirstMyLocation){
//                    isFirstMyLocation = false;
//                    LatLng curLatlng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
//                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
//                }

//                searchText.setText("");
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }
}
